<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" :footer="null">
    <div class="categories-form-container">
      <a-form :model="formData" layout="vertical" class="categories-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="分类名称" required>
                <a-input v-model:value="formData.name" placeholder="请输入分类名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分类代码" required>
                <a-input v-model:value="formData.code" placeholder="请输入分类代码" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="分类描述">
            <a-textarea v-model:value="formData.description" placeholder="请输入分类描述" :rows="3" />
          </a-form-item>
        </div>

        <!-- 样式设置 -->
        <div class="form-section">
          <h3 class="section-title">样式设置</h3>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="分类图标">
                <div class="emoji-form-row">
                  <a-input v-model:value="icon" placeholder="点击右侧图标选择" readonly class="emoji-input" />
                  <template v-if="icon">
                    <a-button type="text" size="small" @click="icon = ''" class="clear-emoji">清除</a-button>
                  </template>
                  <template v-else>
                    <Vue3Emoji size="small" :options-name="optionsName" @click-emoji="selectEmoji" />
                  </template>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="排序权重">
                <a-input-number v-model:value="formData.sortOrder" placeholder="请输入排序权重" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="分类颜色">
            <div class="color-selector">
              <div class="color-presets">
                <div
                  v-for="color in colorPresets"
                  :key="color"
                  class="color-option"
                  :style="{ background: color }"
                  :class="{ active: formData.color === color }"
                  @click="formData.color = color"
                ></div>
              </div>
              <div v-if="formData.color" class="selected-color" :style="{ background: formData.color }">
                <span class="color-value">{{ formData.color }}</span>
                <a-button type="text" size="small" @click="formData.color = ''" class="clear-color"> 清除 </a-button>
              </div>
            </div>
          </a-form-item>
        </div>

        <!-- 状态设置 -->
        <div class="form-section">
          <h3 class="section-title">状态设置</h3>
          <a-form-item label="分类状态" required>
            <a-radio-group v-model:value="formData.status">
              <a-radio :value="0">禁用</a-radio>
              <a-radio :value="1">启用</a-radio>
            </a-radio-group>
          </a-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isUpdate ? '更新' : '保存' }}
          </a-button>
        </div>
      </a-form>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, reactive, defineOptions } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveOrUpdate } from '../BlogCategories.api';
  import { message } from 'ant-design-vue';
  import Vue3Emoji from 'vue3-emoji';

  defineOptions({ name: 'BlogCategoriesModal' });

  // Emits声明
  const emit = defineEmits(['register', 'success']);

  const submitLoading = ref(false);
  const isUpdate = ref(false);
  const icon = ref('');

  // Emoji选项配置
  const optionsName = {
    'Smileys & Emotion': '表情',
    'Food & Drink': '食物&饮料',
    'Animals & Nature': '动物&自然',
    'Travel & Places': '旅行&地点',
    'People & Body': '人物&身体',
    Objects: '物品',
    Symbols: '符号',
    Flags: '旗帜',
    Activities: '活动',
  };

  // 颜色预设
  const colorPresets = ref([
    '#FFD59E', // 奶油橙
    '#FFB7B2', // 柔粉红
    '#B5EAD7', // 薄荷绿
    '#C7CEEA', // 雾霾蓝紫
    '#FFDAC1', // 奶油杏
    '#E2F0CB', // 浅青绿
    '#B5D8FA', // 柔蓝
    '#E0BBE4', // 柔紫
    '#FFB347', // 柔橙
    '#A2D5C6', // 青绿
    '#F7B7A3', // 珊瑚粉
    '#B4AEE8', // 淡紫
    '#F6C6EA', // 浅粉紫
    '#F9F871', // 柔黄
    '#A0CED9', // 蓝绿
  ]);

  // 表单数据
  const formData = reactive({
    id: '',
    name: '',
    code: '',
    description: '',
    color: '',
    icon: '',
    sortOrder: 0,
    status: 1,
    articleCount: 0,
    createdTime: '',
    updatedTime: '',
  });

  // 选择emoji
  const selectEmoji = (val: any) => {
    console.log('选中的emoji', val);
    icon.value = typeof val === 'string' ? val : val.emoji;
  };

  // 表单配置
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 重置表单
    Object.keys(formData).forEach((key) => {
      if (key === 'sortOrder' || key === 'status' || key === 'articleCount') {
        formData[key] = 0;
      } else {
        formData[key] = '';
      }
    });
    formData.status = 1; // 默认启用

    setModalProps({ confirmLoading: false, showCancelBtn: false, showOkBtn: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      // 表单赋值
      Object.keys(data.record).forEach((key) => {
        if (formData.hasOwnProperty(key)) {
          formData[key] = data.record[key];
        }
      });
      icon.value = data.record.icon || '';
    } else {
      icon.value = '';
    }
  });

  // 设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增分类' : '编辑分类'));

  // 取消操作
  const handleCancel = () => {
    closeModal();
  };

  // 表单提交事件
  async function handleSubmit() {
    try {
      // 验证必填字段
      if (!formData.name.trim()) {
        message.error('请输入分类名称');
        return;
      }
      if (!formData.code.trim()) {
        message.error('请输入分类代码');
        return;
      }

      formData.icon = icon.value;
      setModalProps({ confirmLoading: true });
      submitLoading.value = true;

      // 提交表单
      await saveOrUpdate(formData, isUpdate.value);

      // 关闭弹窗
      closeModal();
      // 刷新列表
      emit('success');
      message.success(isUpdate.value ? '更新成功' : '保存成功');
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setModalProps({ confirmLoading: false });
      submitLoading.value = false;
    }
  }
</script>

<style lang="less" scoped>
  .categories-form-container {
    padding: 12px 0 0 0;
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    min-height: 420px;
    max-width: 700px;
    margin: 0 auto;
    @media (max-width: 600px) {
      padding: 4px 0 0 0;
      min-height: 320px;
      border-radius: 0;
      max-width: 100vw;
    }
  }

  .categories-form {
    padding: 0 16px;
    @media (max-width: 600px) {
      padding: 0 2px;
    }
  }

  .form-section {
    margin-bottom: 24px;
    padding: 20px;
    background: #f8fafc;
    border-radius: 12px;
    border: 1px solid #e5e7eb;

    .section-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 16px;
      color: #222;
      border: none;
      padding-bottom: 0;
      letter-spacing: 0.5px;
      text-align: left;
    }
  }

  .form-actions {
    text-align: center;
    margin-top: 24px;
    padding: 16px 0;
    border: none;
    background: transparent;
    border-radius: 0;

    .ant-btn {
      margin: 0 6px;
      min-width: 90px;
      font-size: 14px;
      border-radius: 18px;
      height: 34px;
      box-shadow: none;
      border: none;
      font-weight: 500;
      background: #f3f4f6;
      color: #222;
      transition: all 0.18s;

      &:hover {
        background: #e0e7ef;
        color: #2563eb;
      }

      &:active {
        background: #dbeafe;
        color: #2563eb;
      }
    }

    .ant-btn-primary {
      background: linear-gradient(90deg, #3b82f6 60%, #2563eb 100%);
      color: #fff;
      font-weight: 600;
      box-shadow: none;
      border: none;

      &:hover,
      &:active {
        background: linear-gradient(90deg, #2563eb 60%, #3b82f6 100%);
        color: #fff;
      }
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 18px;
  }

  :deep(.ant-input),
  :deep(.ant-input-number),
  :deep(.ant-textarea) {
    border-radius: 8px;
    font-size: 15px;
    min-height: 32px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    box-shadow: none;
    transition: border 0.18s;

    &:focus,
    &:hover {
      border-color: #3b82f6;
      background: #fff;
    }
  }

  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-radio-group) {
    font-size: 15px;

    .ant-radio-inner {
      border-radius: 50%;
      border-color: #d1d5db;
    }

    .ant-radio-checked .ant-radio-inner {
      border-color: #3b82f6;
      background: #3b82f6;
    }
  }

  :deep(.ant-form-item-label > label) {
    font-weight: 400;
    color: #888;
    letter-spacing: 0.2px;
    font-size: 14px;
  }

  .emoji-form-row {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .emoji-input {
    flex: 2;
    min-width: 200px;
    max-width: 320px;
  }

  .clear-emoji {
    color: #999;
    margin-left: 4px;
  }

  .color-selector {
    .color-presets {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      flex-wrap: wrap;

      .color-option {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        cursor: pointer;
        border: 3px solid #fff; // 白色内边框，保证渐变色下清晰
        box-shadow: 0 0 0 1.5px #d1d5db; // 外发光，提升对比度
        transition: all 0.2s;
        position: relative;
        background-clip: padding-box;

        &:hover {
          box-shadow:
            0 0 0 3px #2563eb,
            0 0 0 1.5px #d1d5db;
          border-color: #2563eb;
        }

        &.active {
          border-color: #2563eb;
          box-shadow:
            0 0 0 3px #2563eb,
            0 0 0 1.5px #d1d5db;

          &::after {
            content: '✓';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
            font-size: 14px;
            font-weight: bold;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
            pointer-events: none;
          }
        }
      }
    }

    .selected-color {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      border-radius: 8px;
      color: white;
      font-size: 12px;
      min-height: 40px;
      position: relative;
      overflow: hidden;

      .color-value {
        font-weight: 500;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .clear-color {
        color: rgba(255, 255, 255, 0.9);
        background: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        padding: 2px 6px;

        &:hover {
          color: white;
          background: rgba(0, 0, 0, 0.3);
        }
      }
    }
  }

  :deep(.vue3-emoji) {
    border: none;
    background: transparent;
  }
</style>